package com.itheima.controller;


import com.itheima.common.Result;
import com.itheima.entity.Category;
import com.itheima.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yancy
 * @since 2024-03-07
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        //todo
        category.setCreateUser(1);
        categoryService.save(category);
        return Result.ok("添加成功");
    }

    @GetMapping
    public Result<List<Category>> list(){
        List<Category> cs = categoryService.list();
        return Result.ok(cs);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id){
        Category c = categoryService.getById(id);
        return Result.ok(c);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.updateById(category);
        return Result.ok();
    }

    @DeleteMapping
    public Result delete(Integer id){
        categoryService.removeById(id);
        return Result.ok();
    }
}

